package com.jecy.elasticsearch.demo;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class TransportClientTest {
    public static void main(String[] args) throws IOException {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).
                addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //testGet(transportClient);//get查找
        testDelete(transportClient);//删除
        transportClient.close();
    }

    public static void testGet(TransportClient transportClient) {
        GetResponse getResponse = transportClient.prepareGet("twitter", "tweet", "1").get();

        System.out.println(JSON.toJSONString(getResponse));
    }

    public static void testDelete(TransportClient transportClient) {
        transportClient.prepareDelete("twitter", "tweet", "1").get();
    }
    public static void testIndex(TransportClient transportClient) throws IOException {
        //1
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("user", "kimchy");
        json.put("postDate", new Date());
        json.put("message", "trying out Elasticsearch");
        //2
        XContentBuilder builder = jsonBuilder().startObject()
                .field("user", "kimchy")
                .field("postDate", new Date())
                .field("message", "kimchy").endObject();
        String jsonStr = builder.string();
        IndexResponse response = transportClient.prepareIndex("twitter", "tweet", "1").setSource(jsonStr).get();
    }

}
